package com.ccut.xunfeiSpringboot.controller;


import com.ccut.xunfeiSpringboot.common.AjaxResult;
import com.ccut.xunfeiSpringboot.service.ListenerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
public class ListenerController {

    @Autowired
    private ListenerService listenerService;

    @PostMapping("/listener")
    public AjaxResult listener(MultipartFile file) throws IOException {
        System.out.println("接收到文件：" + file.getOriginalFilename());
        System.out.println("File content type: " + file.getContentType());

        // 检查文件格式
        if (!file.getOriginalFilename().endsWith(".pcm")) {
            return AjaxResult.error("文件格式不支持，请上传 .pcm 文件");
        }

        // 将 MultipartFile 转换为临时文件
        File tempFile;
        try {
            tempFile = File.createTempFile("temp-", ".pcm");
            file.transferTo(tempFile);
        } catch (IOException e) {
            return AjaxResult.error("文件处理失败");
        }
        // 调用服务层进行语音识别
        try {
            String result = listenerService.transcribeAudio(tempFile).join();
            log.info("识别结果：" + result);
            System.out.println("识别结果：" + result);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("识别失败: " + e.getMessage());
        } finally {
            // 删除临时文件
            tempFile.delete();
        }
//        return AjaxResult.success();
    }
}
